package com.example.baselibs.net.interceptor;

import com.example.baselibs.entity.ErrorResult;
import com.example.baselibs.entity.Result;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * 拦截返回的数据作判断，如果是错误信息，需要从新调整返回
 */
public class ResponseInterceptor implements Interceptor {
    @NotNull
    @Override
    public Response intercept(@NotNull Chain chain) throws IOException {
        Response response=chain.proceed(chain.request());
        Gson gson=new GsonBuilder().create();
        MediaType mediaType=null;
        String jsonStr=null;
        Result result=new Result();
        if (response.body()!=null&&response.body().contentType()!=null){
            mediaType=response.body().contentType();
            jsonStr=response.body().string();
            try {
                ErrorResult<Object> errorResult= gson.fromJson(jsonStr, ErrorResult.class);
                if (!errorResult.isStatus()){
                    String str= (String) errorResult.getData();
                    result.setError(str);
                    result.setLogin(errorResult.isLogin());
                    result.setSql(errorResult.getSql());
                    result.setStatus(errorResult.isStatus());
                }
                String resultJson=gson.toJson(result);
                ResponseBody responseBody=ResponseBody.create(resultJson,mediaType);
                return response.newBuilder().body(responseBody).build();
            }catch (Exception e){}

        }
        ResponseBody responseBody=ResponseBody.create(jsonStr,mediaType);
        return response.newBuilder().body(responseBody).build();
    }
}
